package com.server;

import java.util.HashMap;
import java.util.LinkedList;

public class Monitor {
	private HashMap<Integer, LinkedList<byte[]>>	outgoing;
	private HashMap<Integer, LinkedList<byte[]>>	incoming;

	public Monitor()
	{
		outgoing = new HashMap<Integer, LinkedList<byte[]>>();
		incoming = new HashMap<Integer, LinkedList<byte[]>>();
	}

	public synchronized boolean registerClient(int clientId)
	{
		if (outgoing.get(clientId) == null && incoming.get(clientId) == null)
		{
			outgoing.put(clientId, new LinkedList<byte[]>());
			incoming.put(clientId, new LinkedList<byte[]>());
			return true;
		}
		return false;
	}

	public synchronized void postOutgoing(byte[] b, int clientId)
	{
		outgoing.get(clientId).push(b);
		notifyAll();
	}

	public synchronized void postIncoming(byte[] b, int clientId)
	{
		incoming.get(clientId).push(b);
		notifyAll();
	}

	public synchronized byte[] getIncoming(int id)
	{
		if (incoming.get(id) == null)
		{
			return null;
		}
		while (incoming.get(id).isEmpty())
		{
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		notifyAll();
		return incoming.get(id).pop();
	}

	public synchronized byte[] getOutgoing(int id)
	{
		if (outgoing.get(id) == null)
		{
			return null;
		}
		while (outgoing.get(id).isEmpty())
		{
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		notifyAll();
		return outgoing.get(id).pop();
	}
}
